package hc;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.spi.properties.ClusterProperty;
import com.hazelcast.topic.ITopic;
import com.hazelcast.topic.Message;
import com.hazelcast.topic.MessageListener;

import java.time.Instant;

public class C {

    private PerformanceAnalyze performanceAnalyze = new PerformanceAnalyze();

    private HazelcastInstance hz;

    public C(String publicAddress, int port, String member) {
        Config config = new Config();
        config.getNetworkConfig().setPublicAddress(publicAddress).setPort(port);
        config.getNetworkConfig().getJoin().getTcpIpConfig().setEnabled(true)
                .addMember(member);
        config.setProperty(ClusterProperty.EVENT_THREAD_COUNT.getName(), "10");

        hz = Hazelcast.newHazelcastInstance(config);
    }

    public void start() {
        ITopic<Integer> topic = hz.getTopic("topic");
        topic.addMessageListener(new MessageListenerImpl());
        System.out.println("Subscribed");

        performanceAnalyze.start();
    }

    private class MessageListenerImpl implements MessageListener<Integer> {
        public void onMessage(Message<Integer> m) {
            long result = Instant.now().getNano() - m.getMessageObject();
            performanceAnalyze.cpCounter();
            performanceAnalyze.timeDelay(result);

        }
    }
}
